/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ssm.changeunit.command;

import com.ssm.changeunit.persistance.ManagedItemListDAO;
import com.ssm.changeunit.persistance.ManagedItemListDTO;
import com.ssm.changeunit.persistance.PersistanceException;
import com.ssm.changeunit.util.FileUtil;
import com.ssm.changeunit.*;
import com.ssm.changeunit.persistance.DatabaseManager;
import com.ssm.changeunit.persistance.ManagedChangeUnitDAO;
import com.ssm.changeunit.persistance.ManagedChangeUnitDTO;
import java.io.File;
import org.apache.log4j.Logger;
import java.io.IOException;

/**
 *
 * @author 시리우스
 */
public class CheckoutCommandWorker extends CommandWorker {
    private Logger log = Logger.getLogger(CheckoutCommandWorker.class);

    @Override
    public void work(CommandWorkerOptions commandWorkerOptions) throws CommandWorkerException {
        if( commandWorkerOptions == null )
            throw new CommandWorkerException("Option이 null입니다.");
        
        if( !commandWorkerOptions.hasCommandWorkerOption("branch") )
            throw new CommandWorkerException("branch Option이 존재하지 않습니다.");
        
        // Item option을 꺼내옵니다.
        CommandWorkerOption branchCommandWorkerOption = commandWorkerOptions.getCommandWorkerOption("branch");
        
        // Item option에 해당하는 item들을 가져옵니다.
        String[] branches = branchCommandWorkerOption.getValues();
        
        // item의 값이 없는 경우
        if( branches.length == 0 )
            throw new CommandWorkerException("branch 값이 존재하지 않습니다.");
        
        // 데이터베이스 체크
        log.debug("데이터베이스가 존재하는지 검사합니다.");
        
        try {
            if(!DatabaseManager.getInstance().isExists())
                throw new CommandWorkerException("데이터베이스가 존재하지 않습니다.");
        }
        catch(PersistanceException ex) {
            throw new CommandWorkerException(ex);
        }
        
        try {
            String targetBranchName = branches[0];
            
            // 현재 Branch의 ChangeUnitItem을 가져와 삭제
            Branch currentBranch = new BranchFactory().createProduct(Environment.getCurrentBranch());

            // 타겟 Branch의 ChangeUnitItem을 가져와 생성
            ChangeUnit currentChangeUnit = currentBranch.getCurrentChangeUnit();
            
            // 삭제
            for(ChangeUnitItem changeUnitItem: currentChangeUnit.getChangeUnitItems()) {
                String filePath = changeUnitItem.getFilePath();
                
                File file = new File(Environment.ROOT_DIR + filePath);
                
                file.delete();
                
                File parentFile = file.getParentFile();
                
                if(parentFile.list().length == 0)
                    parentFile.delete();
            }
            
            ManagedItemListDAO managedItemListDAO = new ManagedItemListDAO();
            for(ManagedItemListDTO managedItemListDTO : managedItemListDAO.list()) {
                managedItemListDAO.delete(managedItemListDTO.getFilePath());
            }
            
            Branch targetBranch = new BranchFactory().createProduct(targetBranchName);
            
            // 타겟 Branch의 ChangeUnitItem을 가져와 생성
            ChangeUnit targetChangeUnit = targetBranch.getCurrentChangeUnit();
            
            // 생성
            for(ChangeUnitItem changeUnitItem: targetChangeUnit.getChangeUnitItems()) {
                ManagedItemListDTO managedItemListDTO = new ManagedItemListDTO();
                managedItemListDTO.setFilePath(changeUnitItem.getFilePath());
                managedItemListDAO.insert(managedItemListDTO);
                
                FileUtil.saveDataToFile(Environment.ROOT_DIR + changeUnitItem.getFilePath(), new String(changeUnitItem.getRefChangeLog().getContent()));
            }
            
            // Branch 이동
            Environment.setCurrentBranch(targetBranchName);
            
            Branch branch = new BranchFactory().createProduct(Environment.getCurrentBranch());
            
            ManagedChangeUnitDAO managedChangeUnitDAO = new ManagedChangeUnitDAO();
            ManagedChangeUnitDTO managedChangeUnitDTO = managedChangeUnitDAO.find();
            managedChangeUnitDTO.setManagedChangeUnitId(branch.getCurrentChangeUnit().getChangeUnitId());
            managedChangeUnitDAO.update(managedChangeUnitDTO);
        }
        catch(IOException ex) {
            throw new CommandWorkerException(ex);
        }
        catch(CreateException ex) {
            throw new CommandWorkerException(ex);
        }
        catch(PersistanceException ex) {
            throw new CommandWorkerException(ex);
        }
    }
}